<template>
  <div
    class="w-screen min-h-screen flex justify-center gap-[20px] mt-[20px] mb-[40px]"
  >
    <!-- 左侧内容区域 -->
    <div class="w-[840px]">
      <!-- 问题卡片容器 -->
      <div class="w-full bg-white rounded-2xl p-5">
        <!-- 学习计划区域 -->
        <h2 class="text-2xl font-bold text-gray-700 mb-6 text-left">
          学习计划
        </h2>
        <div class="grid grid-cols-3 gap-4 mb-8">
          <template v-if="bankLoading">
            <TopicsBankSkeleton v-for="i in 4" :key="i" />
          </template>
          <template v-else>
            <QuestionBank
              v-for="(card, index) in cardDataList"
              :key="index"
              :cardData="card"
              class="w-full"
            />
          </template>
        </div>
        <!-- 分隔线 -->
        <div class="my-6 h-[1px] bg-[#E5E5E5]"></div>

        <!-- 顶部导航 -->
        <div class="flex flex-wrap gap-2">
          <button
            v-for="nav in navItems"
            :key="nav.id"
            :class="[
              'px-5 py-2 rounded-full text-sm font-medium transition-colors',
              currentNav === nav.id
                ? 'bg-gray-900 text-white'
                : 'bg-[#F2F3F4] hover:bg-gray-100 text-gray-900',
            ]"
            @click="handleNavClick(nav.id)"
          >
            <div class="flex items-center">
              <span v-if="nav.id === 'all'" class="w-4 h-4 mr-2">
                <svg
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                >
                  <path
                    d="M9 4H5a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1Z"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                  <path
                    d="M9 14H5a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1v-4a1 1 0 0 0-1-1Z"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                  <path
                    d="M19 14h-4a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1Z"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                  <path
                    d="M19 4h-4a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1Z"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                  />
                </svg>
              </span>
              <span v-else :class="nav.iconClass" class="mr-2">{{
                nav.icon
              }}</span>
              {{ nav.text }}
            </div>
          </button>
        </div>
        <!-- 子导航 -->
        <div class="flex flex-wrap items-center mt-4 gap-2">
          <div class="flex-none">
            <TopicListButton
              text="题库"
              :options="questionSetOptions"
              :isOpen="currentOpenDropdown === 'questionSet'"
              v-model="selectedQuestionSet"
              @toggle="handleDropdownToggle('questionSet')"
              @select="handleQuestionSetSelect"
            />
          </div>
          <div class="flex-none">
            <TopicListButton
              text="难度"
              :options="difficultyOptions"
              :isOpen="currentOpenDropdown === 'difficulty'"
              v-model="selectedDifficulty"
              @toggle="handleDropdownToggle('difficulty')"
              @select="handleDifficultySelect"
            />
          </div>
          <div class="flex-none">
            <TopicListButton
              text="排序"
              :options="sortOptions"
              :isOpen="currentOpenDropdown === 'sort'"
              v-model="selectedSort"
              @toggle="handleDropdownToggle('sort')"
              @select="handleSortSelect"
            />
          </div>
          <!-- 添加重置按钮 -->
          <div class="flex-none">
            <button
              @click="resetFilters"
              class="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-600 rounded-lg text-sm transition-colors"
            >
              重置
            </button>
          </div>
          <div class="flex-1 min-w-[200px]">
            <div class="relative flex">
              <div class="relative flex-1">
                <Search
                  @click="handleSearch"
                  class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4 cursor-pointer"
                />
                <input
                  type="text"
                  v-model="searchQuery"
                  placeholder="搜索题目、编号或内容"
                  class="w-full pl-10 pr-4 py-2 bg-[#F2F3F4] rounded-l-lg text-sm"
                  @keyup.enter="handleSearch"
                />
              </div>
            </div>
          </div>
          <button
            @click="handleRandomProblem"
            class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg text-sm flex items-center transition-colors"
          >
            <Shuffle class="h-4 w-4 mr-1" />
            随机一题
          </button>
        </div>
        <!-- 将原来的题目列表替换为新组件 -->
        <div class="mt-6">
          <template v-if="loading">
            <ProblemListSkeleton />
          </template>
          <template v-else>
            <ProblemList :problems="problems" />
          </template>
          <!-- 调整分页组件样式 -->
          <div class="flex justify-center items-center py-6">
            <a-pagination
              v-model:current="currentPage"
              v-model:pageSize="pageSize"
              :total="total"
              :default-page-size="20"
              :page-size-options="['10', '20', '30', '50']"
              show-size-changer
              class="pagination-custom"
              @change="handlePageChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧区域 - 使用新的排行榜组件 -->
    <div class="w-[340px]">
      <div class="sticky top-5 w-full">
        <RankingList
          :rankings="rankingList"
          :loading="rankingLoading"
          @period-change="handleRankingPeriodChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import TopicListButton from "../../../components/topics/TopicListButton.vue";
import QuestionBank from "../../../components/topics/TopicsBank.vue";
import TopicsBankSkeleton from "../../../components/topics/TopicsBankSkeleton.vue";
import RankingList from "../../../components/forum/RankingList.vue";
import ProblemList from "../../../components/topics/TopicList.vue";
import ProblemListSkeleton from "../../../components/topics/ProblemListSkeleton.vue";
import { Search, Shuffle, CheckCircle2, Circle, Lock } from "lucide-vue-next";
import { Pagination as APagination } from "ant-design-vue";
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { getBankList, getAllBanks } from "../../../api/frontend/bank.js";
import {
  getHomeTopicList,
  getTopicTypes,
} from "../../../api/frontend/topic.js";
import { topic } from "../../../api/frontend/topic.js";

// 分页相关的响应式变量
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const searchQuery = ref("");
const problems = ref([]); // 保留这个声明

// 添加加载状态
const loading = ref(false);

// 在 script setup 中添加查询参数的响应式引用
const queryParams = ref({
  typeId: null, // 题目类型
  bankId: null, // 题库
  difficulty: null, // 难度
  sort: null, // 排序
  keyword: "", // 搜索关键词
});

// 获取题目列表
const fetchTopicList = async (customParams = {}) => {
  try {
    loading.value = true;
    const params = {
      pageNumber: currentPage.value,
      pageSize: pageSize.value,
      ...queryParams.value, // 合并查询参数
      ...customParams, // 合并自定义参数
    };
    const result = await getHomeTopicList(params);
    if (result.code === 200) {
      problems.value = result.data.data.map((item) => ({
        id: item.id,
        status: item.isDone ? "done" : "none", // 根据 isDone 设置状态
        title: item.title,
        solutions: item.solutionNum?.toString() || "0",
        passRate: item.passingRate + "%",
        difficulty: ["简单", "中等", "困难"][item.difficulty],
        type: "sql",
        thumbNum: parseInt(item.thumbNum) || 0, // 添加点赞数
        isThumb: item.isThumb || false, // 添加点赞状态
      }));
      total.value = parseInt(result.data.total);
    }
  } catch (error) {
    console.error("获取题目列表失败:", error);
  } finally {
    loading.value = false;
  }
};

// 修改分页处理函数
const handlePageChange = (page, size) => {
  currentPage.value = page;
  pageSize.value = size;
  fetchTopicList();
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  queryParams.value.keyword = searchQuery.value;
  fetchTopicList();
};

// 修改 cardDataList 的定义为响应式引用
const cardDataList = ref([]);

// 修改排行榜数据为响应式
const rankingList = ref([]);

// 添加加载状态
const rankingLoading = ref(false);

// 修改获取排行榜数据的方法
const fetchRankingList = async (type = "week") => {
  try {
    rankingLoading.value = true;
    rankingList.value = []; // 清空现有数据
    const result = await topic.getRankList(type);
    if (result.code === 200) {
      rankingList.value = result.data.map((item) => ({
        id: item.userId,
        name: item.nickName,
        avatar: item.avatar,
        solved: item.solvedCount,
      }));
    }
  } catch (error) {
    console.error("获取排行榜数据失败:", error);
  } finally {
    rankingLoading.value = false;
  }
};

// 使用一个统一的 onMounted
onMounted(async () => {
  rankingLoading.value = true;
  try {
    currentNav.value = "0"; // 确保默认选中全部题目
    await Promise.all([
      fetchRankingList(),
      fetchBankList(),
      fetchTopicTypes(),
      fetchBankOptions(),
    ]);
    // 最后才获取题目列表，避免重复请求
    await fetchTopicList();
  } finally {
    rankingLoading.value = false;
  }
});

// 处理排行榜时间周期变化
const handleRankingPeriodChange = (period) => {
  fetchRankingList(period);
};

// 当前选中的导航项
const currentNav = ref("0"); // 默认选中全部题目

// 修改导航数据为响应式
const navItems = ref([{ id: "0", text: "全部题目" }]);

// 修改图标映射为数组形式
const iconList = [
  { icon: "⚡", iconClass: "text-orange-500" },
  { icon: "📊", iconClass: "text-blue-500" },
  { icon: "$", iconClass: "text-green-500" },
  { icon: "⚙", iconClass: "text-purple-500" },
  { icon: "🔍", iconClass: "text-red-500" },
];

// 获取题目类型数据
const fetchTopicTypes = async () => {
  try {
    const result = await getTopicTypes();
    if (result.code === 200) {
      const types = result.data.map((item, index) => ({
        id: item.id,
        text: item.name,
        ...(iconList[index] || { icon: "📌", iconClass: "text-gray-500" }), // 提供默认图标
      }));
      navItems.value = [{ id: "0", text: "全部题目" }, ...types];
    }
  } catch (error) {
    console.error("获取题目类型失败:", error);
  }
};

// 下拉菜单选项数据
const questionSetOptions = ref([]);

// 获取题库下拉列表数据
const fetchBankOptions = async () => {
  try {
    const result = await getAllBanks();
    if (result.code === 200) {
      questionSetOptions.value = result.data.map((item) => ({
        label: item.name,
        value: item.id,
      }));
    }
  } catch (error) {
    console.error("获取题库下拉列表失败:", error);
  }
};

const difficultyOptions = ref([
  { label: "简单", value: "0" },
  { label: "中等", value: "1" },
  { label: "困难", value: "2" },
]);

// 修改标签选项为排序选项
const sortOptions = ref([
  { label: "通过率", value: "1" },
  { label: "最新", value: "2" },
]);

// 处理选择事件
const handleQuestionSetSelect = (item) => {
  queryParams.value.bankId = item.value;
  fetchTopicList();
};

const handleDifficultySelect = (item) => {
  queryParams.value.difficulty = item.value;
  fetchTopicList();
};

// 更新标签选择处理函数
const handleSortSelect = (item) => {
  queryParams.value.sort = item.value;
  fetchTopicList();
};

// 处理导航点击
const handleNavClick = (navId) => {
  if (navId !== currentNav.value) {
    // 只在点击不同项时才切换
    currentNav.value = navId;
    queryParams.value.typeId = navId === "0" ? null : navId;
    fetchTopicList();
  }
};

// 添加当前打开的下拉框 ID
const currentOpenDropdown = ref(null);

// 修改处理函数，添加日志输出以便调试
const handleDropdownToggle = (dropdownId) => {
  console.log("Current:", currentOpenDropdown.value, "Clicked:", dropdownId);
  currentOpenDropdown.value =
    currentOpenDropdown.value === dropdownId ? null : dropdownId;
};

// 添加选中值的响应式引用
const selectedDifficulty = ref("");
const selectedSort = ref("");
const selectedQuestionSet = ref("");

const bankLoading = ref(true);

// 修改获取题库列表函数
const fetchBankList = async () => {
  try {
    bankLoading.value = true;
    const result = await getBankList();
    if (result.code === 200) {
      cardDataList.value = result.data.data;
    }
  } catch (error) {
    console.error("获取题库列表失败:", error);
  } finally {
    bankLoading.value = false;
  }
};

// 重置所有筛选条件的函数
const resetFilters = () => {
  // 重置查询参数
  queryParams.value = {
    typeId: null,
    bankId: null,
    difficulty: null,
    sort: null,
    keyword: "",
  };
  // 重置其他相关状态
  searchQuery.value = "";
  currentNav.value = "0";
  selectedDifficulty.value = "";
  selectedQuestionSet.value = "";
  selectedSort.value = "";
  // 关闭所有下拉框
  currentOpenDropdown.value = null;
  // 重新获取数据
  fetchTopicList();
};

const router = useRouter();

// 修改随机选题的处理函数
const handleRandomProblem = () => {
  if (problems.value && problems.value.length > 0) {
    const randomIndex = Math.floor(Math.random() * problems.value.length);
    const randomProblem = problems.value[randomIndex];
    router.push({
      name: "SqlProblemDetail",
      params: { id: randomProblem.id },
    });
  } else {
    fetchRandomProblem();
  }
};

// 修改获取随机题目函数
const fetchRandomProblem = async () => {
  try {
    loading.value = true;
    const result = await getHomeTopicList({
      pageNumber: 1,
      pageSize: 20,
      // 保持当前的筛选条件
      ...queryParams.value,
    });
    if (result.code === 200 && result.data.data.length > 0) {
      const randomIndex = Math.floor(Math.random() * result.data.data.length);
      const randomProblem = result.data.data[randomIndex];
      router.push({
        name: "SqlProblemDetail",
        params: { id: randomProblem.id },
      });
    }
  } catch (error) {
    console.error("获取随机题目失败:", error);
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
/* 覆盖 Ant Design Vue 的分页图标样式 */
:deep(.ant-pagination) .anticon {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.ant-pagination-item-link) {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
